from typing import List, Optional, Dict
from .player import Player
from .card import Card
from .dungeon import Dungeon
from .enemies import Enemy, get_random_enemy
import random

class Game:
    def __init__(self):
        self.player: Optional[Player] = None
        self.dungeon: Optional[Dungeon] = None
        self.current_floor: int = 1
        self.is_game_over: bool = False
        self.current_room = None
        self.current_turn: int = 1
        self.battle_rewards = None
        
    def start_new_game(self, character_class: str) -> None:
        """开始新游戏"""
        self.player = Player(character_class)
        self.dungeon = Dungeon(self.current_floor)
        self.current_room = self.dungeon.rooms[self.dungeon.current_room]
        
        # 确保第一个房间是战斗房间并生成敌人
        self.current_room["type"] = "combat"
        self.current_room["content"] = {
            "enemy": get_random_enemy(self.current_floor)  # 使用工厂函数创建敌人
        }
        self.is_game_over = False
        self.current_turn = 1
    
    def execute_action(self, action: Dict) -> bool:
        """执行玩家行动"""
        if action["type"] == "card":
            card = action["card"]
            if self.player.stats["current_mana"] >= card.cost:
                # 扣除法力值
                self.player.stats["current_mana"] -= card.cost
                
                # 使用卡牌
                if self.current_room["type"] == "combat":
                    enemy = self.current_room["content"]["enemy"]
                    old_hp = enemy.current_hp
                    
                    # 使用卡牌
                    card.use(self.player, enemy)
                    
                    # 计算造成的伤害
                    damage_dealt = old_hp - enemy.current_hp
                    
                    # 检查敌人是否死亡
                    if enemy.current_hp <= 0:
                        # 生成战斗奖励
                        self.generate_rewards()
                        self.current_room["completed"] = True  # 标记房间完成
                    
                    # 将使用的卡牌放入弃牌堆
                    self.player.hand.remove(card)
                    self.player.discard_pile.append(card)
                    
                    return {
                        "success": True,
                        "damage_dealt": damage_dealt,
                        "card_name": card.name,
                        "target_name": enemy.get_name()
                    }
        return False
    
    def end_turn(self) -> None:
        """结束当前回合"""
        # 重置玩家状态
        self.player.end_turn()
        
        # 如果在战斗中，执行敌人行动
        if self.current_room["type"] == "combat" and not self.current_room["completed"]:
            enemy = self.current_room["content"]["enemy"]
            # 让敌人选择下一个行动
            enemy_action = enemy.take_action()
            
            # 执行敌人行动
            if enemy_action["type"] == "attack":
                damage = max(0, enemy_action["damage"] - self.player.get_defense())
                self.player.stats["current_hp"] -= damage
            elif enemy_action["type"] == "ability":
                # 处理特殊技能效果
                damage = enemy_action["damage"]
                self.player.stats["current_hp"] -= damage
                # 这里可以添加其他特殊效果
            
            return enemy_action
        return None
    
    def generate_rewards(self) -> None:
        """生成战斗奖励"""
        import random
        from .cards import Strike, DoubleStrike
        
        # 生成金币奖励（根据敌人等级增加）
        enemy = self.current_room["content"]["enemy"]
        gold = 10 + (enemy.level * 5) + random.randint(0, 10)
        
        # 立即添加金币奖励
        self.player.add_gold(gold)
        
        # 生成卡牌奖励
        available_cards = [
            Strike(), Strike(), DoubleStrike(),
            # 可以在这里添加更多可能的奖励卡牌
        ]
        reward_cards = random.sample(available_cards, 3)
        
        self.battle_rewards = {
            "gold": gold,
            "cards": reward_cards,
            "selected_card": None
        }
    
    def enter_next_room(self) -> None:
        """进入下一个房间"""
        self.dungeon.current_room += 1
        if self.dungeon.current_room >= len(self.dungeon.rooms):
            self.current_floor += 1
            self.dungeon = Dungeon(self.current_floor)
            self.dungeon.current_room = 0
        
        # 获取新房间
        self.current_room = self.dungeon.rooms[self.dungeon.current_room]
        
        # 确保新房间是战斗房间并生成敌人
        self.current_room["type"] = "combat"
        self.current_room["content"] = {
            "enemy": get_random_enemy(self.current_floor)
        }
        self.current_room["completed"] = False
        
        # 重置战斗奖励
        self.battle_rewards = None 